package com.bstek.weixin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bstek.weixin.dao.WeixinCheckinDao;
import com.bstek.weixin.entity.CheckInCondition;
import com.bstek.weixin.service.ICheckinService;
import com.bstek.weixin.utils.BodyUtil;
import com.bstek.weixin.utils.DateUtil;
import com.bstek.weixin.wxInterface.CheckInInterFace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Description TEDO
 * @Author snail
 * @Date 2019/1/9
 * @Version 1.0
 */
@Service(CheckinImpl.BEAN_ID)
public class CheckinImpl implements ICheckinService {

    public static final String BEAN_ID="msi.weix.checkinImpl";

    @Autowired
    WeixinCheckinDao weixinCheckinDao;

    @Override
    @Transactional
    public boolean getCheckins(CheckInCondition condition) throws Exception {
        if(condition!=null){
            //1、获取微信接口 打卡数据
            //条件的验证
            Date startDate =condition.getStartDate();
            Date endDate =condition.getEndDate();
            if(startDate!=null&&endDate!=null){
                Calendar calendar=Calendar.getInstance();
                calendar.setTime(startDate);
                int start=calendar.get(Calendar.DAY_OF_YEAR);
                calendar.setTime(endDate);
                int end=calendar.get(Calendar.DAY_OF_YEAR);
                if((end-start)>20){
                    throw new Exception("查询时间跨度不能超过20天");
                }
            }else{
                throw new NullPointerException("打卡查询时间不能为空..");
            }
            //用户列表
            int users=condition.getUsers().length;
            if(users>=100){
                throw new Exception("用户列表不超过100个..");
            }
            String checkBody= BodyUtil.checkinBody(condition.getCheckinType(),
                    condition.getStartDate(),condition.getEndDate(),condition.getUsers());
            JSONObject checkInJson=CheckInInterFace.getCheckinData(checkBody);
            //2、解析打卡数据,,并且保存到临时表
            if(checkInJson==null){
                throw new Exception("微信打卡数据接口查询失败，返回json数据为null..");
            }
            //3、删除查询日期内的打卡信息
            Map<String,Object> delMap=new HashMap<String,Object>();
            delMap.put("startDate", DateUtil.getDateStr("yyyy-MM-dd",startDate));
            delMap.put("endDate", DateUtil.getDateStr("yyyy-MM-dd",endDate));
            weixinCheckinDao.deleteCheckInByTime(delMap);
            //4、保存查询的打卡信息
            boolean flag=analysisCheckin(checkInJson);
            return flag;
        }else{
            throw new NullPointerException("打卡条件不能为空");
        }

    }

    /**
    *@Description  解析打卡数据
    *@Author snail
    *@Date 2019/1/13
    *@return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
    **/
    public boolean analysisCheckin(JSONObject checkInJson)
        throws Exception{
        //删除日期内的数据
        if(checkInJson!=null){
            String errcode=checkInJson.getString("errcode");
            if ("0".equals(errcode)) {
                JSONArray jsonArray= checkInJson.getJSONArray("checkindata");
                if(jsonArray.size()>0){
                    for (int i = 0; i <jsonArray.size(); i++) {
                        JSONObject checkInFo=jsonArray.getJSONObject(i);
                        Map<String,Object> checkMap=checkInFo.getInnerMap();
                        if(checkMap!=null&&checkMap.size()>0){
                            //时间处理
                            Integer intTime=(Integer) checkMap.get("checkin_time");
                            if(intTime!=null&&intTime>0L){
                                Long longTime=new Long(intTime);
                                Date checkDate=new Date(longTime*1000);
                                checkMap.put("checkin_time",checkDate);
                                System.out.println("时间戳："+longTime +"时间"+checkDate);
                            }else{
                                throw new Exception("查询微信打卡时间为null...");
                            }

                        }
                        //保存打卡数据
                        System.out.println("打卡MAP："+checkMap);
                        weixinCheckinDao.saveCheckIn(checkMap);
                    }
                    return true;
                }else{
                    //未查询到任何打卡数据
                    return true;
                }

            }else{
                throw new Exception("查询打卡数据失败...");
            }
        }
        return false;
    }

}
